<template>
  <div class="card-out-container">
    <a-form
      layout="inline"
      v-if="showMore"
      class="multi-line-search-form"
      id="makeSearchBoxId"
    >
      <template v-for="(item, index) in makeListSearchParams" :key="index">
        <a-form-item :label="item.title" v-if="item.show">
          <a-input
            v-if="item.type == 'input'"
            :maxLength="29"
            v-model:value.trim="queryParam[item.key]"
            :placeholder="`${$t('common.pleaseInput')} ${item.title}`"
            @keyup.enter="loadData"
            allowClear
          />
          <a-select
            v-model:value="queryParam[item.key]"
            :placeholder="`${$t('common.pleaseSelect')} ${item.title}`"
            v-if="item.type == 'select'"
            allowClear
            mode="multiple"
          >
            <a-select-option
              v-for="(el, i) in prodTypeList"
              :value="el.name"
              :key="i"
              >{{ el.name }}</a-select-option
            >
          </a-select>
          <a-range-picker
            v-if="item.type == 'time'"
            v-model:value="queryParam[item.key]"
            :placeholder="[$t('common.startDate'), $t('common.endDate')]"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
          />
        </a-form-item>
      </template>
      <a-form-item>
        <a-space>
          <a-button type="primary" @click="loadData">{{$t('common.see')}}</a-button>
          <a-button @click="searchReset">{{$t('common.reset')}}</a-button>
          <a-button type="link" @click="filterSearch">{{$t('common.filterConfig')}}</a-button>
        </a-space>
      </a-form-item>
    </a-form>
    <CustomTable
      storeTableName="makeListTable"
      rowKey="id"
      :loading="loading"
      :dataSource="dataSource"
      :columns="columns"
      :rowSelection="
        isEnvLocal
          ? null
          : {
              selectedRowKeys: selectedRowKeys,
              getCheckboxProps: checkboxProps,
              onChange: onSelectChange,
              fixed: 'left',
            }
      "
      :pagination="ipagination"
      :scroll="{ x: 1000, y: tableHeight }"
      @change="handleTableChange"
      :showMore="showMore"
      :operateMargin="true"
      :resizeColumns="true"
    >
      <template #operateLeft>
        <div class="operate-left">
          <a-button v-if="isEnvLocal" type="primary" @click="syncData(syncDataAry)">{{ $t('common.sync') }}</a-button>
          <span v-else>
            <div class="divBackgroundImg2">
              <a-button type="primary" class="addBtn" style="margin-right: 0!important;" @click="operateClick({ value: 0 })">
                <template #icon><PlusSquareOutlined /></template>{{ $t('common.addNew') }}
              </a-button>
            </div>
            <a-button class="ml-10" ghost type="warning" :disabled="!selectedRowKeys.length" @click="handleDelete(null)">{{$t('common.delMore')}}</a-button>
<!--            <a-upload name="file" :action="url.uplaodUrl" :headers="uploadHeaders" @change="handleImportExcel" :show-upload-list="false" :before-upload="beforeUpload">-->
<!--              <a-button ghost type="primary">{{$t('common.importExcel')}}</a-button>-->
<!--            </a-upload>-->
          </span>
        </div>
      </template>
      <template #operateRight>
        <div class="slot-operate-right">
          <a-input-search
            v-model:value.trim="fuzzySearch"
            enter-button
            :placeholder="$t('hangManage.makeNo')"
            v-if="!showMore"
            @search="loadData"
          />
          <a-button class="ml-10" @click="toggleMore" type="primary" ghost
            >{{$t('common.highFilter')}}</a-button
          >
        </div>
      </template>
      <template #bodyCell="{ scope }">
        <template v-if="scope.column.key === 'moNo'">
          <!--<a-badge :count=" !scope.record.isMoProcess ? 'NEW' : '0'"  :offset="[15,0]" :number-style="{backgroundColor: '#FB602D',color: '#fff','border-radius': '1px','font-size': '10px','padding': '0 1px','line-height': '14px','height': '14px'}" >-->
          <!--   <span class="code-link" @click="handleDrawDetail(scope.record)">{{ scope.record.moNo }}</span>-->
          <!--</a-badge>-->
          <a-badge :offset="[13,0]" >
            <template #count v-if="scope.record.isNew ">
              <span class="newiconImg"></span>
            </template>
             <span class="code-link" @click="handleDrawDetail(scope.record)">{{ scope.record.moNo }}</span>
          </a-badge>

        </template>
        <template v-else-if="scope.column.key === 'status'">
          <a-tag :color="scope.text == 1 ? 'processing' : scope.text == 2 ? 'success' : 'warning' ">{{ getText(statusList, scope.text, "value") }}</a-tag>
        </template>
        <template v-else-if="scope.column.key === 'alreadyProductQty'">
          <span
            class="code-link"
            @click="operateClick({ value: 8 }, scope.record)"
            >{{ scope.record.alreadyProductQty }}</span
          >
        </template>

        <template v-else-if="scope.column.key === 'operate'">
          <span class="table-operate-container">
            <a-badge :count=" !scope.record.isMoProcess ? '!' : '0'" size="small" :offset="[0,0]" :number-style="{backgroundColor: '#FB602D',color: '#fff',}" >
              <a-button type="link" class="primary-link" @click="onProcOperate(scope.record)">{{ $t('other.processTable') }}</a-button>
            </a-badge>
            <span v-if="!isEnvOnline">
              <a-divider type="vertical" />
              <a-badge :count=" (!scope.record.isMoRoadmap && scope.record.isMoProcess) ? '!' : '0'" size="small" :offset="[0,0]" :number-style="{backgroundColor: '#FB602D',color: '#fff',}" >
                <a-button :disabled="!scope.record.isMoProcess" type="link" class="primary-link" @click="onRouteOperate(scope.record)">{{$t('hangManage.road')}}</a-button>
              </a-badge>
            </span>
            <span v-if="!isEnvLocal">
              <a-divider type="vertical" />
              <a-dropdown>
                <span class="code-link">
                  {{$t('hangManage.more')}}
                  <DownOutlined />
                </span>
                <template #overlay>
                  <a-menu>
                    <template
                      v-for="item in operateInfo[scope.record.status || 0]"
                      :key="item.value"
                    >
                      <a-menu-item divided v-if="showOpt(scope.record, item)">
                        <span @click="operateClick(item, scope.record)">{{
                          item.label
                        }}</span>
                      </a-menu-item>
                    </template>
                  </a-menu>
                </template>
              </a-dropdown>
            </span>
          </span>
        </template>
      </template>
    </CustomTable>
    <copy-make-modal ref="copyMakeModal" @ok="copyOk" />
    <SyncDataModal ref="syncDataModalRef" />
    <FilterParamsModal ref="filterParamsModalRef" @ok="onParamsConfigOK" />
    <DetailDraw ref="detailForm"></DetailDraw>
    <addProcessModal ref="addProcessModalRef" @ok="loadData" />
    <editProcessModal ref="editProcessModalRef" @ok="loadData" />
    <viewProcessModal
      ref="viewProcessModalRef"
      @operateProc="onProcModalOperate"
    />
    <addRouteModal ref="addRouteModalRef" @ok="loadData" />
    <editRouteModal ref="editRouteModalRef" @ok="loadData" />
    <viewRouteModal
      ref="viewRouteModalRef"
      @operateRoute="onRouteModalOperate"
    />
  </div>
</template>

<script>
import { ListMixinPm } from "@/mixin/listMixinPm.js";
import { getText, getLocalStorage } from "@/utils";
import { DownOutlined , PlusSquareOutlined } from "@ant-design/icons-vue";
import CopyMakeModal from "./modules/copyMakeModal.vue";
import {listColumns, statusList, operateInfo, operateInfoDev, makeListSearchParams, syncDataAry } from "./modules/makeConfig";
import CustomTable from "@/components/commonTable/customTable.vue";
import SyncDataModal from "@/components/syncModal/syncDataModal.vue";
import DetailDraw from "./modules/detailDraw.vue";
import FilterParamsModal from "@/components/filterParamsModal/filterParamsModal.vue";
import addProcessModal from "@/views/makeManage/makeProcess/newModules/addProcessModal.vue";
import editProcessModal from "@/views/makeManage/makeProcess/newModules/editProcessModal.vue";
import viewProcessModal from "@/views/makeManage/makeProcess/newModules/viewProcessModal.vue";
import addRouteModal from "@/views/makeManage/routeChart/modules/addRouteModal.vue";
import editRouteModal from "@/views/makeManage/routeChart/modules/editRouteModal.vue";
import viewRouteModal from "@/views/makeManage/routeChart/modules/viewRouteModal.vue";
import { store } from "@/store";
import { mapState } from "vuex";
export default {
  name: "makeList",
  mixins: [ListMixinPm],
  components: {
    DownOutlined,
    CopyMakeModal,
    CustomTable,
    SyncDataModal,
    FilterParamsModal,
    DetailDraw,
    addProcessModal,
    editProcessModal,
    viewProcessModal,
    addRouteModal,
    editRouteModal,
    viewRouteModal,
    PlusSquareOutlined,
  },
  data() {
    return {
      storeName: ["getMake", "getAllMake"],
      url: {
        list: "/api/mo/mo/page",
        delete: "/api/mo/mo/delete",
        changeStatus: "/api/mo/mo/update-status",
        sync: "/api/system/iot/sync-cloud-data",
        uplaodUrl: "/api/mo/mo/import-data",
      },
      columns: listColumns,
      statusList: statusList,
      operateInfo: process.env.VUE_APP_CONFIG ? operateInfo : operateInfoDev,
      copyInfo: {},
      fuzzySearchName: "moNo",
      isEnvOnline: process.env.VUE_APP_CONFIG == "online",
      syncDataAry: syncDataAry,
      makeListSearchParams: [],
      searchTimeAry: ["DeliveryDate", "ProductDate", "Time", "UpdateTime"],
      multipleSelect: ["productTypeList"],
      todayTimeMillisecond: 0,
    };
  },
  computed: {
    ...mapState({
      prodTypeList: (state) => state.normalData.prodTypeList,
      tabs: (state) => state.setting.tabs,
    }),
  },
  methods: {
    getText,
    checkboxProps(record) {
      return {
        // 有排产单就禁止{{ $t('common.del') }}
        disabled: record.isScheduleBill,
        name: `${record.isScheduleBill}`,
      };
    },
    showOpt(record, menuItem) {
      let { status, isScheduleBill } = record;
      let flag = true;
      if (status == 0 && menuItem.value == 2 && isScheduleBill) flag = false
      if(menuItem.value == 10 && !record.isMoProcess) flag = false
      return flag;
    },
    handleDrawDetail(record) {
      this.$router.push({
        path: "/makeManage/makeList/details",
        query: { id: record.id },
      });
    },
    onProcOperate(record) {
      record.isMoProcess
        ? this.$refs.viewProcessModalRef.open({ moId: record.id })
        : this.$refs.addProcessModalRef.open({ moId: record.id });
    },
    async onProcModalOperate(type, record) {
      type == "add"
        ? await this.$refs.addProcessModalRef.open(record)
        : await this.$refs.editProcessModalRef.open(record);
      this.$refs.viewProcessModalRef &&
        this.$refs.viewProcessModalRef.onCancel();
    },
    onRouteOperate(record) {
      record.isMoRoadmap
        ? this.$refs.viewRouteModalRef.open({ moId: record.id })
        : this.$refs.addRouteModalRef.open({ moId: record.id });
    },
    async onRouteModalOperate(type, record) {
      type == "add"
        ? await this.$refs.addRouteModalRef.open(record)
        : await this.$refs.editRouteModalRef.open(record);
      this.$refs.viewRouteModalRef && this.$refs.viewRouteModalRef.onCancle();
    },
    operateClick(item, record) {
      switch (item.value) {
        case 0: // {{ $t('common.addNew') }}
          this.$router.push("/makeManage/makeList/add");
          break;
        case 1: // {{ $t('common.editor') }}
          this.$router.push({
            path: "/makeManage/makeList/edit",
            query: { id: record.id },
          });
          break;
        case 2: // {{ $t('common.del') }}
          this.handleDelete(record.id);
          break;
        case 3: // 复制({{ $t('common.addNew') }})
          this.copyInfo = record;
          this.$refs.copyMakeModal.open();
          break;
        case 4: // 标记为完成t('common.state')
          this.changeStatus(record.id, 2);
          break;
        case 5: // 标记为生产t('common.state')
          this.changeStatus(record.id, 1);
          break;
        case 7: // 远程排产
          this.$router.push({
            path: "/makeManage/addSchedule",
            query: { id: record.id },
          });
          break;
        case 8: // 排产明细
          this.$refs.detailForm.openDraw(record);
          break;
        case 9: // {{ $t('common.addNew') }}排产单
          this.$router.push({
            path: "/hangManage/wipInfo/add",
            query: { moId: record.id },
          });
          break;
        case 10: // t('menu.mo:manufactureorder:edit')
          this.$router.push({
            path: "/makeManage/aiSchedule",
            query: { moId: record.id },
          });
          break;
        default:
          break;
      }
    },
    copyOk(list) {
      this.$router.push({
        path: "/makeManage/makeList/copy",
        query: { id: this.copyInfo.id, copy: list },
      });
    },
    changeStatus(id, status) {
      this.confirmChangeStatus(
        this.url.changeStatus,
        { id, status },
        this.$t('common.ok')+ this.$t('other.alter') + this.$t('common.state') + '?'
      );
    },
    filterSearch() {
      this.$refs.filterParamsModalRef.open(this.makeListSearchParams);
    },
    initTableHeight() {
      this.$nextTick(() => {
        if (this.showMore) {
          let formHeight = `${
            document.getElementById("makeSearchBoxId").clientHeight + 340
          }px`;
          this.tableHeight = `calc(100vh - ${formHeight})`;
        } else {
          this.tableHeight = "calc(100vh - 320px)";
        }
      });
    },
    onParamsConfigOK(checkedAry) {
      this.makeListSearchParams.forEach((i) => {
        i.show = checkedAry.includes(i.key);
      });
      localStorage.setItem(
        "makeListSearchParams",
        JSON.stringify(this.makeListSearchParams)
      );
      this.initTableHeight();
    },
  },
  async created() {
    this.makeListSearchParams = getLocalStorage("makeListSearchParams") || makeListSearchParams;
    await store.dispatch("getProdType");
    let date = new Date()
    let newDate = new Date(date.getFullYear(),date.getMonth(),date.getDate())
    this.todayTimeMillisecond = newDate.getTime()
  },
};
</script>